package com.xiaoming.mojcodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.exception.NotModifiedException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class dockerDemo {
    public static void main(String[] args) throws InterruptedException {
        //拉取镜像
        String image="nginx:latest";
        DockerClient dockerClient= DockerClientBuilder.getInstance().build();
        PullImageCmd pullImageCmd=dockerClient.pullImageCmd(image);
        PullImageResultCallback pullImageResultCallback=new PullImageResultCallback(){
            @Override
            public void onNext(PullResponseItem item) {
                super.onNext(item);
            }
        };
        pullImageCmd.exec(pullImageResultCallback)
                .awaitCompletion();
        System.out.println("下载完成");

        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        CreateContainerResponse createContainerResponse = containerCmd
                .withCmd("echo","hello")
                .exec();
        System.out.println(createContainerResponse);
        System.out.println("创建容器成功");
        String containId=createContainerResponse.getId();

        //查看容器状态
        ListContainersCmd listContainersCmd=dockerClient.listContainersCmd();
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        for (Container container : containerList) {
            System.out.println(container);
        }

        //启动容器
        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(containId);
        startContainerCmd.exec();

        //查看日志
        LogContainerResultCallback logContainerResultCallback=new LogContainerResultCallback()
        {
            @Override
            public void onNext(Frame item) {
                System.out.println("日志"+new String(item.getPayload()));
                super.onNext(item);
            }
        };
        dockerClient.logContainerCmd(containId)
                .withStdOut(true)
                .withStdErr(true)
                .exec(logContainerResultCallback)
                .awaitCompletion();


        //删除容器
        dockerClient.removeContainerCmd(containId).exec();
        //删除镜像
       // dockerClient.removeImageCmd(image).exec();
        

    }


}
